<?php

namespace App\Models;

use Validator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Member extends Model
{
    //软删除
    use SoftDeletes;
    protected $fillable = ['username','password','nickname','email'];
    protected $datas = ['caeated_at','updated_at','deleted_at'];
    protected $dateFormat = 'U';

    //会员添加
    public function add($data)
    {
         $rule = [
             'username' => 'bail|required|unique:members',
             'password' => 'required',
             'nickname' => 'required',
             'email' => 'required|email'
         ];

         $msg = [
             'username.required' => '会员名不能为空',
             'username.unique' => '会员名已存在',
             'password.required' => '密码不能为空',
             'password.required' => '密码不能为空',
             'nickname.required' => '昵称不能为空',
             'email.email' => '邮箱格式不正确',
             'email.required' => '邮箱不能为空'
         ];

         $validator = Validator::make($data,$rule,$msg);
         if ($validator->fails()) {
             return $validator->errors()->first();
         }

         $result = $this->create($data);
         if ($result) {
             return 1;
         } else {
             return "添加失败";
         }
    }

    //会员编辑
    public function edit($data) {
        $rule = [
            'username' => 'bail|required',
            'password' => 'required',
            'nickname' => 'required',
            'email' => 'email|required'
        ];

        $msg = [
            'username.required' => '用户名不能为空',
            'password.required' => '密码不能为空',
            'nickname.required' => '昵称不能为空',
            'email.email' => '邮箱格式不正确',
            'email.required' => '邮箱不能为空'
        ];

        $validator = Validator::make($data,$rule,$msg);
        if ($validator->fails()) {
            return $validator->errors()->first();
        }

        $members = $this->find($data['id']);
        $members->username = $data['username'];
        $members->password = $data['password'];
        $members->nickname = $data['nickname'];
        $members->email = $data['email'];
        $result = $members->save();
        if ($result) {
            return 1;
        } else {
            return "编辑失败";
        }
    }
}
